package dao;

import java.util.List;

import model.Customer;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

public class CustomerDAO {
	private final SessionFactory sf = util.NewHibernateUtil.getSessionFactory();

	@SuppressWarnings("unchecked")
	public List<Customer> showAllCustomer() {
		try {
			sf.getCurrentSession().beginTransaction();
			return sf.getCurrentSession().createCriteria(Customer.class).list();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public List<Customer> showAllCustomerByAll(String key) {
		
		sf.getCurrentSession().beginTransaction();
		List<Customer> Customer = sf
				.getCurrentSession()
				.createCriteria(Customer.class)
				.add(Restrictions.or(Restrictions.like("id", "%" + key + "%"),
						Restrictions.or(Restrictions
								.like("id", "%" + key + "%"), Restrictions.or(
								Restrictions.like("name", "%" + key + "%"),
								Restrictions.or(Restrictions.like("address",
										"%" + key + "%"), Restrictions.or(
										Restrictions.like("phone", "%" + key
												+ "%"),
										Restrictions.like("email", "%" + key
												+ "%"))))))).list();
		sf.getCurrentSession().getTransaction().commit();
		return Customer;
	}

	public Customer searchCustomer(String id) {
		try {
			sf.getCurrentSession().beginTransaction();
			Customer cus = (Customer) sf.getCurrentSession().get(Customer.class, id);
			sf.getCurrentSession().getTransaction().commit();
			return cus;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public boolean deleteCustomer(Customer c) {
		try {
			sf.getCurrentSession().beginTransaction();
			sf.getCurrentSession().delete(c);
			sf.getCurrentSession().getTransaction().commit();
			return true;
		} catch (Exception e2) {
			e2.printStackTrace();
			return false;
		}
	}
	public boolean updateCustomer(Customer c) {
		try {
			sf.getCurrentSession().beginTransaction();
			sf.getCurrentSession().saveOrUpdate(c);
			sf.getCurrentSession().getTransaction().commit();
			return true;
		} catch (Exception e2) {
			e2.printStackTrace();
			return false;
		}
	}
	
	



	public boolean insertCustomer(Customer c) {
		try {
			sf.getCurrentSession().beginTransaction();
			sf.getCurrentSession().save(c);
			sf.getCurrentSession().getTransaction().commit();
			return true;
		} catch (Exception em) {
			em.printStackTrace();
			sf.getCurrentSession().getTransaction().rollback();
			return false;
		}
	}
}